﻿using ZeroMQ;
using System.Text;
using Newtonsoft.Json;
using System.Configuration;

namespace Web.Areas.Auction
{
    public sealed class BidRequester
    {
        //private static readonly ZmqContext context;
        private static readonly string ReplyerEndpoint;
        //public readonly static BidRequester Instance = new BidRequester();
        static BidRequester()
        {
            //context = ZmqContext.Create();
            ReplyerEndpoint = ConfigurationManager.AppSettings["replyerEndpoint"] ?? "tcp://127.0.0.1:6000";

        }       

        public bool Open()
        {
            using (var context = ZmqContext.Create())
            using (var requester = context.CreateSocket(SocketType.REQ))
            {
                requester.Connect(ReplyerEndpoint);
                var request = new BidRequest("open");
                var message = JsonConvert.SerializeObject(request);
                requester.Send(message, Encoding.UTF8);
                var result = requester.Receive(Encoding.UTF8);
                return result == "0";
            }
        }

        public bool Close()
        {
            using (var context = ZmqContext.Create())
            using (var requester = context.CreateSocket(SocketType.REQ))
            {
                requester.Connect(ReplyerEndpoint);
                var request = new BidRequest("open");
                var message = JsonConvert.SerializeObject(request);
                requester.Send(message, Encoding.UTF8);
                var result = requester.Receive(Encoding.UTF8);
                return result == "0";
            }
        }

        public string Bid(long userId, long auctionId, string iPAddress)
        {
            using (var context = ZmqContext.Create())
            using (var requester = context.CreateSocket(SocketType.REQ))
            {
                requester.Connect(ReplyerEndpoint);
                var request = new BidRequest("bid", new { userId, auctionId, iPAddress });
                var message = JsonConvert.SerializeObject(request);
                requester.Send(message, Encoding.UTF8);
                var result = requester.Receive(Encoding.UTF8);
                return result;
            }
        }
        //public SkResult<Bidding> Send(BidRequest request)
        //{
        //    var message = JsonConvert.SerializeObject(request);
        //    requester.Send(message, Encoding.UTF8);
        //    var result = requester.Receive(Encoding.UTF8);
        //}
    }
}